package com.my.chapter8;

public class practice13 {
    public static void main(String[] args) {
        ReferenceCounting.main(args);
    }
}

class Shared {
    private int refCount = 0;
    private static long counter = 0;
    private final long id = counter++;

    public Shared(){
        System.out.println("Creating "+this);
    }

    public void addRef(){
        refCount ++;
    }

    protected void dispose(){
        if(--refCount ==0){
            System.out.println("Disposing " + this);
        }
    }

    @Override
    public String toString() {
        return "Shared " + id;
    }

    @Override
    protected void finalize() throws Throwable {
        if(refCount != 0){
            System.out.println("Error, 引用计数不为0");
        }
        super.finalize();
    }
}

//组成类
class Composing{
    private Shared shared;
    private static long counter = 0;
    private final long id = counter ++;

    public Composing(Shared shared){
        System.out.println("Creating "+ this);
        this.shared = shared;
        shared.addRef();
    }

    protected void dispose() {
        System.out.println("dispose " + this);
        shared.dispose();
    }
    @Override
    public String toString() {
        return "Composing " + id;
    }


}

//引用计数
class ReferenceCounting {
    public static void main(String[] args) {
        Shared shared = new Shared();
        Composing[] composing = {
                new Composing(shared),
                new Composing(shared),
                new Composing(shared),
                new Composing(shared),
                new Composing(shared),
                new Composing(shared)
        };
        for(Composing c:composing){
            c.dispose();
        }
    }
}
